Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:

Input: k = 3, n = 7

Output:

  1. [[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

  1. [[1,2,6], [1,3,5], [2,3,4]]

Solution:

  1. public class Solution {
  2. public List<List<Integer>> combinationSum3(int k, int n) {
  3. List<List<Integer>> res = new ArrayList<List<Integer>>();
  4. helper(k, n, 1, new ArrayList<Integer>(), res);
  5. return res;
  6. }
  7. private void helper(int k, int n, int index, List<Integer> sol, List<List<Integer>> res) {
  8. if (n == 0 && k == sol.size()) {
  9. res.add(new ArrayList<Integer>(sol));
  10. return;
  11. }
  12. if (index > 9 || n < 0) {
  13. return;
  14. }
  15. for (int i = index; i <= 9; i++) {
  16. sol.add(i);
  17. helper(k, n - i, i + 1, sol, res);
  18. sol.remove(sol.size() - 1);
  19. }
  20. }
  21. }